package com.monika.main.base;

import com.monika.main.system.factory.LogManager;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author:whh
 * @date: 2023-02-22 21:24
 * <p></p>
 */
@Configuration
public class RestTemplateConfig {



    @Primary
    @Bean("customRestTemplate")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .connectionPool(new ConnectionPool(100, 300, TimeUnit.SECONDS))
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        restTemplate.setRequestFactory(new OkHttp3ClientHttpRequestFactory(client));
        restTemplate.setInterceptors(Collections.singletonList(customClientHttpRequestInterceptor()));
        return restTemplate;
    }


    /**
     * 自定义拦截器
     * 1、打印请求API
     * 2、统计耗时
     *
     * @return
     */
    public ClientHttpRequestInterceptor customClientHttpRequestInterceptor() {
        return (request, body, execution) -> {
            long start = System.currentTimeMillis();
            HttpHeaders headers = request.getHeaders();
            headers.add("Connection","close");
            ClientHttpResponse response = execution.execute(request, body);
            LogManager.LOG().sys_http_client_log(null).info("URI->{}，METHOD->{}，耗时->{}ms", request.getURI(), request.getMethod(), (System.currentTimeMillis() - start));
            return response;
        };

    }
}
